import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/badge_icon.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/common/widget/safe_cached_network_image.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/feedback/data/model/feedback_dialogue_model.dart';
import 'package:casdon/modules/feedback/providers/feedback_provider.dart';
import 'package:casdon/modules/me/domain/enums/service_order_category.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:video_player/video_player.dart';

class FeedbackDetailScreen extends ConsumerStatefulWidget {
  final String feedbackInfoId;
  final String title;

  const FeedbackDetailScreen({
    super.key,
    required this.feedbackInfoId,
    required this.title,
  });

  @override
  ConsumerState<FeedbackDetailScreen> createState() =>
      _FeedbackDetailScreenState();
}

class _FeedbackDetailScreenState extends ConsumerState<FeedbackDetailScreen> {
  bool _isFinishing = false;

  @override
  Widget build(BuildContext context) {
    final dialoguesAsync = ref.watch(
      feedbackDialogueListProvider(widget.feedbackInfoId),
    );

    return Scaffold(
      backgroundColor: context.colorScheme.surface,
      appBar: CommonAppBar(title: '反馈详情'),
      body: dialoguesAsync.when(
        data: (items) => items.isEmpty
            ? _buildEmptyState(context)
            : _buildTimeline(context, items),
        loading: () => const Center(child: CommonLoadingWidget()),
        error: (error, stack) => _buildError(context, error),
      ),
      bottomNavigationBar: _buildBottomActionBar(context),
    );
  }

  Widget _buildTimeline(
    BuildContext context,
    List<FeedbackDialogueModel> items,
  ) {
    return ListView.separated(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      itemBuilder: (context, index) {
        final dialogue = items[index];
        return _DialogueBubble(dialogue: dialogue);
      },
      separatorBuilder: (_, __) => SizedBox(height: 12.w),
      itemCount: items.length,
    );
  }

  Widget _buildError(BuildContext context, Object error) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '加载失败，请重试',
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
          SizedBox(height: 12.h),
          TextButton(
            onPressed: () => ref.refresh(
              feedbackDialogueListProvider(widget.feedbackInfoId),
            ),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Text(
        '暂无对话记录',
        style: context.textTheme.bodyMedium?.copyWith(
          color: context.customColorThemeNonNull.textColor2,
        ),
      ),
    );
  }

  Widget _buildBottomActionBar(BuildContext context) {
    Widget buildButton({
      required IconData icon,
      required String label,
      required VoidCallback? onTap,
      bool isLoading = false,
    }) {
      final iconWidget = isLoading
          ? SizedBox(
              width: 18.w,
              height: 18.w,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(
                  context.colorScheme.primary,
                ),
              ),
            )
          : Icon(
              icon,
              size: 18.w,
              color: context.customColorThemeNonNull.textColor1,
            );
      return Expanded(
        child: OutlinedButton.icon(
          onPressed: onTap,
          icon: iconWidget,
          label: Text(
            label,
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
          style: OutlinedButton.styleFrom(
            padding: EdgeInsets.symmetric(vertical: 10.h),
            side: BorderSide(
              color:
                  context.customColorThemeNonNull.gray2 ?? Colors.grey.shade300,
            ),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
      );
    }

    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            buildButton(
              icon: Icons.thumb_up_outlined,
              label: '已解决',
              onTap: _isFinishing ? null : () => _handleFinishFeedback(context),
              isLoading: _isFinishing,
            ),
            SizedBox(width: 12.w),
            buildButton(
              icon: Icons.thumb_down_outlined,
              label: '未解决',
              onTap: () => FeedbackContinueRoute(
                feedbackInfoId: widget.feedbackInfoId,
              ).push(context),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _handleFinishFeedback(BuildContext context) async {
    if (_isFinishing) return;
    setState(() {
      _isFinishing = true;
    });

    try {
      final usecase = ref.read(finishFeedbackUsecaseProvider);
      await usecase.execute(widget.feedbackInfoId);
      if (!context.mounted) return;
      ToastUtil.show("感谢您的反馈，我们将不断完善体验!");
      context.router.maybePop();
    } catch (_) {
      if (mounted) {
        ToastUtil.show('操作失败，请稍后重试');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isFinishing = false;
        });
      }
    }
  }
}

class _DialogueBubble extends StatelessWidget {
  final FeedbackDialogueModel dialogue;

  const _DialogueBubble({required this.dialogue});

  @override
  Widget build(BuildContext context) {
    final isService = dialogue.isServiceSide;
    final isSubject = dialogue.isSubject;
    final isPushAfterSale = dialogue.isPushAfterSale == 1;
    final alignment = CrossAxisAlignment.start;
    final bubbleColor = isSubject
        ? isService
              ? Colors.transparent
              : Colors.white
        : Colors.white;
    final nameText = isService ? '凯度客服' : '反馈内容';
    final nameColor = isService
        ? context.colorScheme.primary
        : context.customColorThemeNonNull.warning5;

    return Column(
      crossAxisAlignment: alignment,
      children: [
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(12.w),
          decoration: BoxDecoration(
            color: bubbleColor,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                nameText,
                style: context.textTheme.bodyMedium?.copyWith(color: nameColor),
              ),
              SizedBox(height: 8.h),
              if (dialogue.content.isNotEmpty)
                Text(
                  dialogue.content,
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  ),
                ),

              SizedBox(height: 8.h),

              Row(
                children: [
                  if (dialogue.imageUrls.isNotEmpty) ...[
                    SizedBox(height: 8.h),
                    _MediaAttachmentGrid(
                      items: dialogue.imageUrls,
                      isVideo: false,
                    ),
                  ],

                  if (dialogue.videoUrls.isNotEmpty) ...[
                    SizedBox(height: 8.h),
                    _MediaAttachmentGrid(
                      items: dialogue.videoUrls,
                      isVideo: true,
                    ),
                  ],
                ],
              ),
              SizedBox(height: 8.h),
              Text(
                dialogue.createTime,
                style: context.textTheme.bodyMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor2,
                ),
              ),
              SizedBox(height: 16.h),

              if (isPushAfterSale) ...[
                Divider(
                  height: 1.w,
                  color:
                      context.customColorThemeNonNull.gray2 ??
                      Colors.grey.shade300,
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () => ServiceOrderPostRoute(
                    initialCategory: ServiceOrderCategory.repair,
                  ).push(context),
                  child: Padding(
                    padding: EdgeInsets.symmetric(vertical: 12.w),
                    child: Row(
                      children: [
                        BadgeIcon(
                          imagePath: Assets.images.feedbackRepair.path,
                          size: 36.w,
                        ),
                        SizedBox(width: 8.w),
                        Text(
                          '立即前往【报装报修】',
                          style: context.textTheme.bodyMedium?.copyWith(
                            color: context.customColorThemeNonNull.textColor1,
                          ),
                        ),
                        const Spacer(),
                        Icon(
                          Icons.chevron_right,
                          size: 24.w,
                          color: context.customColorThemeNonNull.textColor2,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ],
    );
  }
}

// 视频缩略图组件
class _VideoThumbnail extends StatefulWidget {
  final String videoPath;

  const _VideoThumbnail({required this.videoPath});

  @override
  State<_VideoThumbnail> createState() => _VideoThumbnailState();
}

class _VideoThumbnailState extends State<_VideoThumbnail> {
  VideoPlayerController? _controller;
  bool _isLoading = true;
  bool _hasError = false;
  bool _isNetworkSource = false;
  String? _snapshotUrl;

  @override
  void initState() {
    super.initState();
    _loadThumbnail();
  }

  Future<void> _loadThumbnail() async {
    try {
      final uri = Uri.tryParse(widget.videoPath);
      final isNetwork = uri != null && uri.hasScheme && uri.host.isNotEmpty;
      if (isNetwork) {
        _isNetworkSource = true;
        _snapshotUrl = _buildSnapshotUrl(widget.videoPath);
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
        return;
      }

      _controller = VideoPlayerController.file(File(widget.videoPath));
      await _controller!.initialize();
      await _controller!.seekTo(Duration.zero);
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator(strokeWidth: 2));
    }

    if (_isNetworkSource) {
      return SafeCachedNetworkImage(
        imageUrl: _snapshotUrl ?? widget.videoPath,
        fit: BoxFit.cover,
      );
    }

    if (_hasError || _controller == null || !_controller!.value.isInitialized) {
      return const Center(child: Icon(Icons.videocam, size: 40));
    }

    return SizedBox.expand(
      child: FittedBox(
        fit: BoxFit.cover,
        child: SizedBox(
          width: _controller!.value.size.width,
          height: _controller!.value.size.height,
          child: VideoPlayer(_controller!),
        ),
      ),
    );
  }

  String _buildSnapshotUrl(String url) {
    const snapshotParams =
        'x-oss-process=video/snapshot,t_0,f_jpg,w_600,m_fast';
    if (url.contains('x-oss-process')) return url;
    final separator = url.contains('?') ? '&' : '?';
    return '$url$separator$snapshotParams';
  }
}

class _MediaAttachmentGrid extends StatelessWidget {
  final List<String> items;
  final bool isVideo;

  const _MediaAttachmentGrid({required this.items, required this.isVideo});

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: List.generate(items.length, (index) {
          return Padding(
            padding: EdgeInsets.only(left: index == 0 ? 0 : 8.w),
            child: _buildMediaPreview(
              context: context,
              url: items[index],
              isVideo: isVideo,
              gallery: items,
              index: index,
            ),
          );
        }),
      ),
    );
  }

  Widget _buildMediaPreview({
    required BuildContext context,
    required String url,
    required bool isVideo,
    List<String>? gallery,
    int index = 0,
  }) {
    bool _isNetwork(String value) {
      final uri = Uri.tryParse(value);
      return uri != null && uri.hasScheme && uri.host.isNotEmpty;
    }

    Widget _buildImage() {
      if (_isNetwork(url)) {
        return SafeCachedNetworkImage(imageUrl: url);
      }
      return Image.file(
        File(url),
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return const Icon(Icons.image, size: 40);
        },
      );
    }

    return GestureDetector(
      onTap: () {
        if (isVideo) {
          VideoPlayerRoute(title: null, url: url).push(context);
        } else {
          ImageBrowserRoute(
            imageUrls: gallery ?? [url],
            initialIndex: index,
          ).push(context);
        }
      },
      child: Container(
        width: 80.w,
        height: 80.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(
            color:
                context.customColorThemeNonNull.gray2 ?? Colors.grey.shade300,
          ),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8.r),
          child: Stack(
            fit: StackFit.expand,
            children: [
              isVideo ? _VideoThumbnail(videoPath: url) : _buildImage(),
              if (isVideo)
                Container(
                  color: Colors.black.withOpacity(0.25),
                  alignment: Alignment.center,
                  child: const Icon(
                    Icons.play_circle_filled,
                    color: Colors.white,
                    size: 30,
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
